import React, { useState } from 'react';
import { Form, Input, Upload, Select, Button, message, Row, Col, Card, Tabs } from 'antd';
import { UploadOutlined, UserOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { userApi } from '../../api/userApi';
import { setUser } from '../../store/userSlice';

const { Option } = Select;
const { TabPane } = Tabs;

const Profile = () => {
  const [form] = Form.useForm();
  const user = useSelector(state => state.user.currentUser);
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(false);

  // 头像上传配置
  const uploadProps = {
    name: 'avatar',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  // 保存个人资料
  const handleProfileSubmit = async (values) => {
    try {
      setLoading(true);
      const response = await userApi.updateProfile(user.id, values);
      message.success('个人资料更新成功！');
      // 更新 Redux store 中的用户信息
      dispatch(setUser(response.data));
    } catch (error) {
      message.error('更新失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 更新学习偏好
  const handlePreferencesSubmit = async (values) => {
    try {
      setLoading(true);
      await userApi.updatePreferences(user.id, values);
      message.success('学习偏好设置已更新！');
    } catch (error) {
      message.error('设置失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="profile-container">
      <Row gutter={[24, 24]}>
        <Col span={6}>
          <Card className="user-info-card">
            <div className="user-avatar">
              <Upload {...uploadProps}>
                {user.avatar ? (
                  <img src={user.avatar} alt="avatar" />
                ) : (
                  <Button icon={<UserOutlined />}>上传头像</Button>
                )}
              </Upload>
            </div>
            <div className="user-basic-info">
              <h3>{user.nickname || '未设置昵称'}</h3>
              <p>{user.email}</p>
            </div>
          </Card>
        </Col>

        <Col span={18}>
          <Card>
            <Tabs defaultActiveKey="1">
              <TabPane tab="基本资料" key="1">
                <Form
                  form={form}
                  layout="vertical"
                  initialValues={user}
                  onFinish={handleProfileSubmit}
                >
                  <Form.Item
                    label="昵称"
                    name="nickname"
                    rules={[{ required: true, message: '请输入昵称' }]}
                  >
                    <Input placeholder="请输入昵称" />
                  </Form.Item>

                  <Form.Item
                    label="性别"
                    name="gender"
                  >
                    <Select placeholder="请选择性别">
                      <Option value="male">男</Option>
                      <Option value="female">女</Option>
                      <Option value="other">其他</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    label="个人简介"
                    name="bio"
                  >
                    <Input.TextArea
                      rows={4}
                      placeholder="介绍一下自己吧"
                      maxLength={200}
                      showCount
                    />
                  </Form.Item>

                  <Form.Item
                    label="手机号码"
                    name="phone"
                    rules={[
                      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                    ]}
                  >
                    <Input placeholder="请输入手机号码" />
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading}>
                      保存修改
                    </Button>
                  </Form.Item>
                </Form>
              </TabPane>

              <TabPane tab="学习偏好" key="2">
                <Form
                  layout="vertical"
                  onFinish={handlePreferencesSubmit}
                  initialValues={user.preferences}
                >
                  <Form.Item
                    label="感兴趣的领域"
                    name="interests"
                  >
                    <Select mode="multiple" placeholder="请选择感兴趣的领域">
                      <Option value="programming">编程</Option>
                      <Option value="language">语言</Option>
                      <Option value="art">艺术</Option>
                      <Option value="science">科学</Option>
                      <Option value="business">商业</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    label="每日学习时间"
                    name="studyTime"
                  >
                    <Select placeholder="请选择预期学习时间">
                      <Option value="0.5">30分钟以内</Option>
                      <Option value="1">1小时</Option>
                      <Option value="2">2小时</Option>
                      <Option value="3">3小时以上</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    label="学习提醒"
                    name="reminders"
                  >
                    <Select mode="multiple" placeholder="请选择提醒时间">
                      <Option value="morning">早上</Option>
                      <Option value="afternoon">下午</Option>
                      <Option value="evening">晚上</Option>
                    </Select>
                  </Form.Item>

                  <Form.Item>
                    <Button type="primary" htmlType="submit" loading={loading}>
                      保存偏好设置
                    </Button>
                  </Form.Item>
                </Form>
              </TabPane>
            </Tabs>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Profile; 